var orm      = require('../../../../');
var settings = require('../../config/settings');

var connection = null;

function setup(db, cb) {
  require('./message')(orm, db);
  require('./comment')(orm, db);
  require('./hospital')(orm, db);
  require('./hospitalsect')(orm, db);
  require('./feedback')(orm, db);
  require('./doctor')(orm, db);
  require('./tag')(orm, db);
  require('./chatrecord')(orm, db);
  require('./user')(orm, db);
  require('./friend')(orm, db);
  require('./payrecord')(orm, db);
  require('./evaluation')(orm, db);
  require('./family')(orm, db);
  require('./medicalrecord')(orm, db);
  require('./evaluation')(orm, db);
  require('./appointment')(orm, db);
  return cb(null, db);
}

module.exports = function (cb) {
  if (connection) return cb(null, connection);

  orm.connect(settings.database, function (err, db) {
    if (err) return cb(err);

    db.settings.set('instance.returnAllErrors', true);
    setup(db, cb);
  });
};
